package org.jeecgframework.web.controller;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsExtWarrantyServiceI;
import org.jeecgframework.web.service.CbsServiceErrorLogServiceI;
import org.jeecgframework.web.service.CbsServiceServiceI;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.sendWxMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: cbs_ext_warranty
 * @date 2017-01-06 16:00:57
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsExtWarrantyController")
public class CbsExtWarrantyController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsExtWarrantyController.class);

    @Autowired
    private CbsExtWarrantyServiceI cbsExtWarrantyService;
    @Autowired
    private SystemService systemService;

    @Autowired
    private WxCommonService wxCommonService;
    @Autowired
    private CbsServiceServiceI cbsServiceServiceI;
    @Autowired
    private CbsServiceErrorLogServiceI cbsServiceErrorLogService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * cbs_ext_warranty列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsExtWarranty")
    public ModelAndView cbsExtWarranty(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsextwarranty/cbsExtWarrantyList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsExtWarrantyEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsExtWarranty, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsExtWarrantyService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * cbs_ext_warranty新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsExtWarranty.getId())) {
            cbsExtWarranty = cbsExtWarrantyService.getEntity(CbsExtWarrantyEntity.class, cbsExtWarranty.getId());
            req.setAttribute("cbsExtWarrantyPage", cbsExtWarranty);
        }
        return new ModelAndView("com/zybk/cbsextwarranty/cbsExtWarranty-add");
    }


    /*
     * 原微信申请设备维保功能
     * */

    /**
     * 添加cbs_ext_warranty
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "cbs_ext_warranty添加成功";
        try {
            cbsExtWarranty.setServiceId(wxCommonService.generateServiceId(WxCommonService.ServiceEnum.YBSQ));
            cbsExtWarrantyService.save(cbsExtWarranty);
            wxCommonService.sendServiceMail(WxCommonService.ServiceEnum.YBSQ, cbsExtWarranty.getId());
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "cbs_ext_warranty添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setObj(cbsExtWarranty.getServiceId());
        j.setMsg(message);
        return j;
    }


    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }

    /**
     * 现微信申请设备维保功能
     * 开发人：马宏刚
     * 时间：2018-04
     */
    @RequestMapping(params = "doAddNew")
    @ResponseBody
    public AjaxJson doAddNew(HttpServletRequest request) {
        String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
        String name = oConvertUtils.getString(request.getSession().getAttribute("name"));
        System.out.println("openId--" + openId);
        TSUser user = systemService.singleResult("from TSUser where openId='" + openId + "'");
        String createBy = "";
        String createName = "";
        if (StringUtil.isNotEmpty(user) && StringUtil.isNotEmpty(user.getUserName())) {
            createBy = user.getUserName();
        } else {
            createBy = openId;
        }
        if (StringUtil.isNotEmpty(user)&& StringUtil.isNotEmpty(user.getRealName())) {
            createName = user.getRealName();
        } else {
            createName = name;
        }
        System.out.println("openId--" + openId);
        AjaxJson j = new AjaxJson();
        CbsServiceEntity service = new CbsServiceEntity();
        message = "申请设备维保成功";

        String eqNumber = request.getParameter("equipmentNum");
        String extendedYear = request.getParameter("extendedYear");
        String sn = request.getParameter("sn");
        CbsServiceTypeEntity sType1 = systemService.singleResult("from CbsServiceTypeEntity where type=0 and name='咨询'");
        CbsServiceTypeEntity sType2 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name='维保咨询'");
        try {
            service.setZyCinemaName(request.getParameter("cinemaName"));
            service.setTypename(request.getParameter("cinemaChain"));
            service.setContactsName(request.getParameter("contactsName"));
            service.setContactsPhone(request.getParameter("contactsPhone"));
            service.setEmail(request.getParameter("contactsEmail"));
            if (StringUtil.isNotEmpty(eqNumber)&& !eqNumber.equals("")) {
                service.setEquipmentNum(Integer.valueOf(eqNumber));
            }
            if (StringUtil.isNotEmpty(extendedYear)&& !extendedYear.equals("")) {
                service.setExtendedYear(Integer.valueOf(extendedYear));
            }
            service.setDescription("设备台数:" + eqNumber + ";延保年限:" + extendedYear);
            service.setServiceType1(sType1);
            service.setServiceType2(sType2);
            service.setSourceType("2");
            service.setStatus("1");
            service.setSn(request.getParameter("sn"));
            service.setSpeedStatus("0");
            ZyEquipmentSpareEntity zyEquipmentSpare = systemService.singleResult("from ZyEquipmentSpareEntity where sn='" + sn + "'");
            if (StringUtil.isNotEmpty(zyEquipmentSpare)) {
                service.setZyEquipmentSpareId(zyEquipmentSpare);
                service.setRepairEndDate(zyEquipmentSpare.getRepairEndDate()); //保修截止日期
            }
            ZyCinemaEntity cinema = systemService.singleResult("from ZyCinemaEntity where name='" + request.getParameter("cinemaName") + "'");
            if (StringUtil.isNotEmpty(cinema)) {
                service.setZyCinemaId(cinema);
                service.setProvince(cinema.getProvince());
                if (StringUtil.isNotEmpty(cinema.getCity())) {
                    TSTerritory city = systemService.get(TSTerritory.class, cinema.getCity());
                    service.setCity(city);
                }
                service.setAddress(cinema.getAddress());
            }
            String hql = "from ZyContactsEntity where cellphone1='" + request.getParameter("contactsPhone") + "' or cellphone2='" + request.getParameter("contactsPhone") + "'";
            List<ZyContactsEntity> zyContacts = systemService.findHql(hql);
            if (zyContacts.size() > 0) {
                service.setZyContactsId(zyContacts.get(0));
            }
            //新的服务单号
            Map noMap = cbsServiceServiceI.getNo();
            String code = (String) noMap.get("no");

            service.setCode(code);
            service.setCreateBy(createBy);
            service.setCreateName(createName);
            service.setCreateDate(new Date());
            systemService.save(service);

            /*设备序列号异常*/
            List<ZyEquipmentSpareEntity> zyEquipmentSpareListService = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", sn);
            if(zyEquipmentSpareListService.size()==0){
                cbsServiceErrorLogService.doAdd(service, sn, "无设备序列号");
            }

            //添加日志
            wxCommonService.addServiceLog(service.getId());

            /*给服务单客户联系人发送微信提醒*/
//			wxCommonService.sendWxMsg(service,user);
            //调用微信接口发送
            List<Map<String, String>> list = new ArrayList<>();
            String serviceCode = "";
            if (StringUtil.isNotEmpty(service)) {
                serviceCode = service.getCode();
            }
            String content = "尊敬的客户：您的放映机<" + sn + ">的服务申请已提交，服务单号：<" + serviceCode + ">。我们会在30分钟内与您联系。【中影巴可客服部】";
            if (StringUtil.isNotEmpty(openId)) {
                Map<String, String> map = new HashMap<>();
                map.put("openid", openId);
                map.put("message", content);
                list.add(map);
            }
            wxCommonService.sendMsgForWx(list);
            //发送邮件给HD
            wxCommonService.sendMail(service);

            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "cbs_ext_warranty添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setObj(service.getCode());
        j.setMsg(message);
        return j;
    }

    /**
     * cbs_ext_warranty编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsExtWarranty.getId())) {
            cbsExtWarranty = cbsExtWarrantyService.getEntity(CbsExtWarrantyEntity.class, cbsExtWarranty.getId());
            req.setAttribute("cbsExtWarrantyPage", cbsExtWarranty);
        }
        return new ModelAndView("com/zybk/cbsextwarranty/cbsExtWarranty-update");
    }

    /**
     * 更新cbs_ext_warranty
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "cbs_ext_warranty更新成功";
        CbsExtWarrantyEntity t = cbsExtWarrantyService.get(CbsExtWarrantyEntity.class, cbsExtWarranty.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsExtWarranty, t);
            cbsExtWarrantyService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "cbs_ext_warranty更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除cbs_ext_warranty
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsExtWarranty = systemService.getEntity(CbsExtWarrantyEntity.class, cbsExtWarranty.getId());
        message = "cbs_ext_warranty删除成功";
        try {
            cbsExtWarrantyService.delete(cbsExtWarranty);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "cbs_ext_warranty删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除cbs_ext_warranty
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "cbs_ext_warranty删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsExtWarrantyEntity cbsExtWarranty = systemService.getEntity(CbsExtWarrantyEntity.class,
                        id
                );
                cbsExtWarrantyService.delete(cbsExtWarranty);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "cbs_ext_warranty删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsextwarranty/cbsExtWarrantyUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsExtWarrantyEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsExtWarranty, request.getParameterMap());
        List<CbsExtWarrantyEntity> cbsExtWarrantys = this.cbsExtWarrantyService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "cbs_ext_warranty");
        modelMap.put(NormalExcelConstants.CLASS, CbsExtWarrantyEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("cbs_ext_warranty列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsExtWarrantys);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsExtWarrantyEntity cbsExtWarranty, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "cbs_ext_warranty");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsExtWarrantyEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsExtWarrantyEntity> listCbsExtWarrantyEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsExtWarrantyEntity.class, params);
                for (CbsExtWarrantyEntity cbsExtWarranty : listCbsExtWarrantyEntitys) {
                    cbsExtWarrantyService.save(cbsExtWarranty);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
}
